<template>
  <div class="project-list-wrapper">
    <!-- <div class="module-name">项目列表</div> -->
    <div class="search-bar">
      <el-form ref="formRef" size="mini" :model="filters" label-width="150px">
        <el-row :gutter="24" class="filters-row-box">
          <el-col :span="8">
            <el-form-item label="项目编号：">
              <el-input
                style="width: 80%"
                clearable
                placeholder="请输入"
                maxlength="30"
                v-model.trim="filters.projectCode"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="项目名称：">
              <el-input style="width: 80%" clearable placeholder="请输入" maxlength="30" v-model="filters.projectName">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="注册类项目：">
              <el-select v-model="filters.registerProject" placeholder="请选择">
                <el-option v-for="item in projectTypeList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="filters-row-box">
          <el-button type="primary" size="mini" @click="handleSearch" icon="el-icon-search">查询</el-button>
          <el-button type="default" size="mini" @click="handleResent" icon="el-icon-refresh">重置</el-button>
          <column-control
            v-model="tableColumns"
            size="mini"
            style="margin-left: 8px; margin-right: 8px"
          ></column-control>
        </el-row>
      </el-form>
    </div>
    <div class="details-layout">
      <el-table
        :data="projectList"
        stripe
        style="width: 100%"
        size="mini"
        row-key="id"
        :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }"
        :tree-props="{ children: 'children' }"
      >
        <template v-for="(column, index) in tableColumns">
          <el-table-column
            v-if="column.visible"
            :width="column.width"
            :key="index"
            :min-width="column.minWidth"
            :label="column.name"
            :show-overflow-tooltip="true"
            align="center"
          >
            <template slot-scope="scope">
              <div v-if="column.key === 'operate'">
                <el-button
                  v-for="vItem in scope.row.versions"
                  :key="vItem.id"
                  type="text"
                  @click="handleEntryProject(scope.row, vItem)"
                >{{ vItem.projectType === 2 ? '测试项目' : '进入项目' }}</el-button
                >
              </div>
              <div v-if="column.key === 'registerProject'">
                <span>{{ scope.row[column.key] === '1' ? '是' : '否' }}</span>
              </div>
              <span v-else>{{ scope.row[column.key] }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.pageNo"
          :page-sizes="[10, 20, 50]"
          :page-size="pagination.pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>
      </div>
      <!-- 测试项目选择角色和中心的弹窗 -->
      <el-dialog :visible="entryVisible" title="进入测试项目" width="500px" @close="handleCancel">
        <el-form ref="formEntryRef" label-width="120px" :model="formEntryData" :rules="formEntryRules">
          <el-form-item label="项目名称：">
            {{ formEntryData.name }}
          </el-form-item>
          <el-form-item label="项目环境：">
            {{ formEntryData.environment }}
          </el-form-item>
          <el-form-item label="选择角色：" prop="roleValue">
            <el-select style="width: 80%" size="mini" v-model="formEntryData.roleValue" @change="handleRoleChange">
              <el-option v-for="item in roleOptions" :key="item.id" :value="item.id" :label="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="coreSelectVis" label="选择中心：" prop="coreValue">
            <el-select
              style="width: 80%; margin-right: 4px"
              size="mini"
              v-model="formEntryData.coreValue"
              multiple
            >
              <el-option
                v-for="item in coreOptions"
                :key="item.coreId"
                :value="item.coreId"
                :label="item.coreName"
              ></el-option>
            </el-select>
            <el-button size="mini" type="primary" @click="handleSelectAll()">全选</el-button>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleCancel()" size="mini">取 消</el-button>
          <el-button type="primary" @click="handleConfirm()" size="mini">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 正式项目 -->
      <el-dialog :visible="officialVisible" title="进入正式项目" width="500px" @close="handleOfficialCancel">
        <el-form ref="officialRef" :model="officialData" label-width="120px" :rules="officialRules">
          <el-form-item label="项目名称：">
            {{ officialData.name }}
          </el-form-item>
          <el-form-item label="项目环境：">
            {{ officialData.environment }}
          </el-form-item>
          <el-form-item label="角色：" prop="role">
            <el-select v-model="officialData.role" style="width: 80%" size="mini" :disabled="true">
              <el-option
                v-for="item in roleOfficialOptions"
                :key="item.id"
                :label="`${item.name}（${item.code}）`"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择中心：" prop="core">
            <el-select multiple clearable v-model="officialData.core" style="width: 80%" size="mini">
              <el-option
                v-for="item in coreOfficialOptions"
                :key="item.coreId"
                :label="item.coreName"
                :value="item.coreId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleOfficialCancel()" size="mini">取 消</el-button>
          <el-button type="primary" @click="handleOfficialConfirm()" size="mini">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { mapActions } from 'vuex'
import { projectTypeList, projectHeaders } from './data'
import moduleRouter from '@/router/module-router.js'

export default {
  name: 'users-manage',

  data() {
    return {
      projectTypeList,
      projectList: [],
      tableColumns: projectHeaders,
      filters: {
        registerProject: '',
        projectCode: '',
        projectName: '',
      },
      pagination: {
        pageSize: 10,
        pageNo: 1,
      },
      total: 0,
      entryVisible: false,
      projectId: '',
      projectDatabaseId: '',
      roleOptions: [],
      coreOptions: [],
      formEntryData: {
        roleValue: '',
        coreValue: [],
        name: '',
        environment: '',
      },
      formEntryRules: {
        roleValue: [{ required: true, message: '请填写', trigger: 'blur' }],
        coreValue: [{ required: true, message: '请填写', trigger: 'blur' }],
      },
      officialVisible: false,
      // 正式项目
      roleOfficialOptions: [],
      coreOfficialOptions: [],
      coreSelectVis: true,
      officialData: {
        role: '',
        core: [],
      },
      officialRules: {
        role: [{ required: true, message: '请填写', trigger: 'blur' }],
        core: [{ required: true, message: '请填写', trigger: 'blur' }],
      },
      standardRoleArr: ['MCA', 'ReadOnlyAll', 'Medical', 'DM', '', 'PM', 'DBB', 'DBBAdmin'],
    }
  },
  mounted() {
    this.getProjectList()
  },

  methods: {
    ...mapActions('projectList', [
      'qryServiceProjectList',
      'deleteProject',
      'getProjectRoleListByUserAPI',
      'getListByRoleAPI',
    ]),
    ...mapActions('roleManage', ['getRoleDataAPI']),
    ...mapActions('centralManagement', ['getCentralManagementAPI']),
    ...mapActions('subjectInformation', ['getUpdateSubjectInfo']),
    ...mapActions('userData', ['getListMenus', 'getPermissionInfo']),
    ...mapActions('projectPersonRoleManage', ['recordLoginProjectAPI']),

    // 获取角色对应的项目菜单列表
    async getRoleHaveMenuList(roleId) {
      const params = {
        roleId,
      }
      const res = await this.getListByRoleAPI({ params })
      localStorage.setItem('project-menu-permission', JSON.stringify(res.data))
    },

    // 选择角色
    handleRoleChange(val) {
      const obj = this.roleOptions.find(item => item.id === val)
      const roleCode = obj.code
      this.formEntryData.roleCode = obj.code
      if (this.standardRoleArr.includes(roleCode)) {
        this.coreSelectVis = false
        const arr = []
        this.coreOptions.forEach(item => {
          arr.push(item.coreId)
        })
        this.formEntryData.coreValue = arr
      } else {
        this.coreSelectVis = true
        this.formEntryData.coreValue = []
      }
    },

    // 进入项目重新加载权限菜单
    getUserMenus(projectId, roleId) {
      const params = {
        projectId,
        roleId,
      }
      this.getListMenus({ params }).then(res => {
        const { code, data } = res
        if (code === 200 && data.length > 0) {
          if (data.length === 1 && data[0].children.length === 0) {
            this.$message.error('暂无进入项目权限，请联系管理员~')
            return ''
          }
          localStorage.setItem('system-menu-list', JSON.stringify(res.data))
          this.getUserPermissions(projectId, roleId)
          this.handleRecordUserEnterprojectTime()
          this.$router.push({
            path: moduleRouter.subjectInformationSummary.path,
            name: moduleRouter.subjectInformationSummary.name,
            query: {
              id: this.projectId,
            },
          })
        } else {
          console.log('获取项目菜单、按钮权限异常')
        }
      })
    },

    // 记录用户进入项目时间
    async handleRecordUserEnterprojectTime() {
      const params = {
        projectId: this.projectId,
      }
      this.recordLoginProjectAPI({ params })
    },

    // 进入项目重新查询用户权限菜单
    getUserPermissions(projectId, roleId) {
      const params = {
        projectId,
        roleId,
      }
      this.getPermissionInfo({ params }).then(res => {
        const { code, data } = res
        if (code === 200) {
          localStorage.setItem('user-permissions', JSON.stringify(data.permissions))
        }
      })
    },

    // 获取用户角色
    async getProjectRoleListByUser(projectId) {
      const params = {
        userId: JSON.parse(localStorage.getItem('user-info')).id,
        projectId,
      }
      const res = await this.getProjectRoleListByUserAPI({ params })
      this.roleOfficialOptions = res.data || []
      if (!res.data[0] && !res.data[0].id) {
        this.$message.error('角色异常，请联系系统管理员~')
        return
      }
      this.officialData.role = res.data[0].id || ''
      this.officialData.roleCode = res.data[0].code || ''

      localStorage.setItem('projectRoleCode', res.data[0].code)

      if (this.standardRoleArr.includes(res.data[0].code)) {
        const arr = []
        this.coreOfficialOptions.forEach(item => {
          arr.push(item.coreId)
        })
        this.officialData.core = arr
        this.handleOfficialConfirm()
      } else {
        this.officialVisible = true
      }
    },

    // 获取项目中角色
    async getProjectRoleData() {
      const params = {
        pageSize: 1000,
        pageNo: 1,
        projectId: this.projectId,
      }

      const res = await this.getRoleDataAPI({ params })
      if (res.code === 200) {
        ;(res.data.records || []).forEach(item => {
          item.name = item.name + '(' + item.code + ')'
        })
        this.roleOptions = res.data.records
        localStorage.setItem('project-roles', JSON.stringify(res.data.records))
      }
    },
    // 获取项目中中心
    async getProjectCenterData() {
      const params = {
        projectId: this.projectId,
        projectDatabaseId: this.projectDatabaseId,
      }
      const res = await this.getUpdateSubjectInfo({ params })
      if (res.code === 200) {
        this.coreOptions = res.data
        this.coreOfficialOptions = res.data
      }
    },
    // 全选
    handleSelectAll() {
      this.coreOptions.forEach(item => {
        if (!this.formEntryData.coreValue.includes(item.coreId)) {
          this.formEntryData.coreValue.push(item.coreId)
        }
      })
    },
    // 弹窗取消
    handleCancel() {
      this.$refs.formEntryRef.resetFields()
      this.entryVisible = false
    },
    handleOfficialCancel() {
      this.$refs.officialRef.resetFields()
      this.officialVisible = false
    },
    // 弹窗确认
    // 测试项目
    async handleConfirm() {
      await this.$refs.formEntryRef.validate()
      this.getRoleHaveMenuList(this.formEntryData.roleValue)
      localStorage.setItem('coreIds', JSON.stringify(this.formEntryData.coreValue))
      const selectedCoreList = []
      this.coreOfficialOptions.map((cItem, cIndex) => {
        if (this.formEntryData.coreValue.includes(cItem.coreId)) {
          selectedCoreList.push(cItem)
        }
      })
      localStorage.setItem('coreOfficialOptions', JSON.stringify(selectedCoreList))

      this.$store.commit('layoutHeader/setRoleId', this.formEntryData.roleValue)
      localStorage.setItem('projectRoleCode', this.formEntryData.roleCode)
      this.getUserMenus(localStorage.getItem('sys-project-id'), this.formEntryData.roleValue)
      // this.getUserPermissions(localStorage.getItem('sys-project-id'), this.formEntryData.roleValue)

      // 设置角色名
      let roleName = ''
      this.roleOptions.forEach(item => {
        if (item.id === this.formEntryData.roleValue) {
          roleName = item.name + '(' + item.code + ')'
        }
      })
      this.$store.commit('layoutHeader/setRoleName', roleName)
      // this.$store.commit('layoutHeader/setRoleOptions', this.roleOptions)
      this.$refs.formEntryRef.resetFields()
      this.entryVisible = false
    },
    
    // 正式项目
    async handleOfficialConfirm() {
      this.getRoleHaveMenuList(this.officialData.role)
      localStorage.setItem('coreIds', JSON.stringify(this.officialData.core))
      const selectedCoreList = []
      this.coreOfficialOptions.map((cItem, cIndex) => {
        if (this.officialData.core.includes(cItem.coreId)) {
          selectedCoreList.push(cItem)
        }
      })
      localStorage.setItem('coreOfficialOptions', JSON.stringify(selectedCoreList))
      localStorage.setItem('roleId', this.officialData.role)
      this.$store.commit('layoutHeader/setRoleId', this.officialData.role)
      // 设置角色名
      let roleName = ''
      this.roleOfficialOptions.forEach(item => {
        if (item.id === this.officialData.role) {
          roleName = item.name + '(' + item.code + ')'
        }
      })
      this.getUserMenus(localStorage.getItem('sys-project-id'), this.officialData.role)
      this.getUserPermissions(localStorage.getItem('sys-project-id'), this.officialData.roleValue)

      this.$store.commit('layoutHeader/setRoleName', roleName)

      this.entryVisible = false
    },

    // 查询列表
    getProjectList() {
      const params = {
        ...this.pagination,
        ...this.filters,
      }
      this.qryServiceProjectList({ params }).then(res => {
        const { data, code } = res
        if (code === 200) {
          this.projectList = data.records || []
          this.total = data.total || 0
        }
      })
    },

    // 💭进入项目操作
    async handleEntryProject(record, version) {
      // 设置项目名称
      this.formEntryData.name = record.projectName
      this.officialData.name = record.projectName
      // 设置项目环境
      this.formEntryData.environment = version.projectType === 2 ? '测试环境' : '正式环境'
      this.officialData.environment = version.projectType === 2 ? '测试环境' : '正式环境'
      // 设置项目id
      this.projectId = record.id
      // 设置项目数据库版本
      this.projectDatabaseId = version.id
      await this.getProjectCenterData()
      // ⭐测试项目
      if (version.projectType === 2) {
        this.entryVisible = true
        this.getProjectRoleData()
        // 储存环境
        localStorage.setItem('environment', 1)
      }
      // ⭐正式项目
      if (version.projectType === 3) {
        // 进入正式项目时，判断用户是否为超级管理员
        const userIsSuperAdmin = JSON.parse(localStorage.getItem('user-info')).roleList.some(
          item => item.code === 'super_admin'
        )
        const coreIds = []
        this.coreOfficialOptions.forEach(item => {
          coreIds.push(item.coreId)
        })
        localStorage.setItem('coreIds', JSON.stringify(coreIds))
        console.log('this.coreOfficialOptions', this.coreOfficialOptions, JSON.stringify(coreIds))

        if (userIsSuperAdmin) {
          localStorage.setItem('coreOfficialOptions', JSON.stringify(this.coreOfficialOptions))
          this.$store.commit('layoutHeader/setRoleId', JSON.parse(localStorage.getItem('user-info')).roleList[0].id)
          localStorage.setItem('project-menu-permission', localStorage.getItem('system-menu-list'))
          const params = {
            userId: JSON.parse(localStorage.getItem('user-info')).id,
            projectId: this.projectId,
          }
          const res = await this.getProjectRoleListByUserAPI({ params })
          this.roleOfficialOptions = res.data || []
          // 设置角色名
          this.$store.commit('layoutHeader/setRoleName', '超级管理员')
          this.$router.push({
            path: moduleRouter.subjectInformationSummary.path,
            name: moduleRouter.subjectInformationSummary.name,
            query: {
              id: this.projectId,
            },
          })
        } else {
          // this.officialVisible = true
          this.getProjectRoleListByUser(record.id)
        }
        // 储存环境
        localStorage.setItem('environment', 2)
      }
      // 菜单
      localStorage.setItem('showMenuType', 5)
      // 储存项目数据库id
      localStorage.setItem('project-database-Id', version.id) // projectDatabaseId
      // 储存项目id
      localStorage.setItem('sys-project-id', record.id) // projectId
      // 储存项目编码
      this.$store.commit('layoutHeader/setSysProjectCode', record.projectCode)
    },

    // 分页pageSize change事件
    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.getProjectList()
    },

    // 分页
    handleCurrentChange(index) {
      this.pagination.pageNo = index
      this.getProjectList()
    },

    // 重置并重新查询列表
    handleResent() {
      this.filters = {
        registerProject: '',
        projectCode: '',
        projectName: '',
      }
      this.pagination.pageNo = 1
      this.getProjectList()
    },

    // 查询操作
    handleSearch() {
      this.pagination.pageNo = 1
      this.getProjectList()
    },

    // 删除
    handleDelete(row) {
      const params = {
        id: row.id,
      }
      this.$confirm('确定删除该条数据吗？', '删除提示', {
        type: 'warning',
      }).then(res => {
        this.deleteProject({ params }).then(res => {
          if (res.code === 200) {
            this.$message({ message: '删除成功', type: 'success' })
            this.getProjectList()
          }
        })
      })
    },
  },
}
</script>
<style lang="scss" scoped>
@import './index.scss';
</style>
